/*
 * @Description: 所有人员实时位置视图
 * @Author: zy
 * @Date: 2021-04-15 19:38:12
 * @LastEditors: zy
 * @LastEditTime: 2021-04-19 16:00:50
 */
import * as d3 from 'd3'
var dupCount = 0
// var color = d3.scaleLinear(d3.schemeCategory10)
export function renderPosition (people) {
//   let t = d3.transition().duration(750)
  let gsensors = d3.select('.sensors').selectAll('g').select('rect')
  let svg = d3.select('#canvas').select('svg')
  let gPeople = svg.selectAll('.people')
    .data(people, d => (d.user_id))

  gPeople.transition()
    .duration(750)
    .attr('cx', function (d) {
      gsensors.each(function (o) {
        if (o.sid === d.sid) {
          let rect = d3.select(this)
          d.cx = parseFloat(rect.attr('x'))
          d.cy = parseFloat(rect.attr('y'))
          d.dx = parseFloat(rect.attr('width')) * Math.random()
          d.dy = parseFloat(rect.attr('height')) * Math.random()
        }
      })
      if (d.sid < 20000) {
        return d.cx + d.dx
      } else {
        console.log('disapear', d3.select(this).attr('cx'))
        d3.select(this).attr('r', 0)
        return parseFloat(d3.select(this).attr('cx'))
      }
    })
    .attr('cy', function (d) {
      if (d.sid < 20000) {
        return (d.cy + d.dy)
      } else {
        return parseFloat(d3.select(this).attr('cy'))
      }
    })
    .style('fill', 'green')

  gPeople.enter()
    .append('circle')
    .attr('class', 'people')
    .attr('cx', function (d) {
      gsensors.each(function (o) {
        if (o.sid === d.sid) {
          let rect = d3.select(this)
          d.cx = parseFloat(rect.attr('x'))
          d.cy = parseFloat(rect.attr('y'))
          d.dx = parseFloat(rect.attr('width')) * Math.random()
          d.dy = parseFloat(rect.attr('height')) * Math.random()
        }
      })
      return d.cx
    })
    .attr('cy', d => d.cy)
    .attr('r', 2)
    .style('fill', function (d) {
      let dupIndex = -1
      for (let i = 0; i < people.length; ++i) {
        if (d.user_id === people[i].user_id && d.sid !== people[i].sid) {
          dupIndex = dupCount + 1
          dupCount++
        }
      }
      if (dupIndex === -1) {
        return 'blue'
      } else {
        return 'red' // color(dupIndex)
      }
    })
    .style('opcaity', 0.6)
    .transition()
    .duration(2000)
    .attr('cx', d => (d.cx + d.dx))
    .attr('cy', d => (d.cy + d.dy))

  gPeople.exit()
    .transition()
    .duration(2000)
    .attr('r', 0)
    .remove()

  gPeople.filter(function () {
    return parseInt(d3.select(this).attr('r')) === 0
  })
    .remove()
}
